package cz.muni.fi.pa165.business.serviceImpl;

import cz.muni.fi.pa165.api.ForestService;
import cz.muni.fi.pa165.api.dto.ForestDTO;
import cz.muni.fi.pa165.business.dao.ForestDAO;
import cz.muni.fi.pa165.business.service.utils.ForestObjectTransformer;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Michal Becak
 */
@Service
public class ForestServiceImpl implements ForestService {

    @Autowired
    private ForestDAO forestDao;

    @PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
    @Transactional
    @Override
    public void createForest(ForestDTO forestDTO) {
        if (forestDTO == null) {
            throw new IllegalArgumentException("ForestDTO is null");
        }
        forestDao.createForest(ForestObjectTransformer.forestDTOToForest(forestDTO));
    }

    @PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
    @Override
    public ForestDTO getForest(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("ForestDTO is null");
        }
        return ForestObjectTransformer.forestToForestDTO(forestDao.getForest(id));
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Transactional
    @Override
    public void updateForest(ForestDTO forestDTO) {
        if (forestDTO == null) {
            throw new IllegalArgumentException("ForestDTO is null");
        }
        forestDao.updateForest(ForestObjectTransformer.forestDTOToForest(forestDTO));
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @Transactional
    @Override
    public void removeForest(ForestDTO forestDTO) {
        if (forestDTO == null) {
            throw new IllegalArgumentException("ForestDTO is null");
        }
        forestDao.removeForest(ForestObjectTransformer.forestDTOToForest(forestDTO));
    }

    @PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
    @Override
    public List<ForestDTO> retrieveAllForests() {
        return ForestObjectTransformer.forestListToForestDTOList(forestDao.retrieveAllForests());
    }

    @PreAuthorize("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')")
    @Override
    public ForestDTO retrieveForestByName(String name) {
        if (name == null) {
            throw new IllegalArgumentException("Name is null");
        }
        return ForestObjectTransformer.forestToForestDTO(forestDao.retrieveForestByName(name));
    }
}
